package com.wangjiacai.utils.web.controller;

import com.wangjiacai.utils.utils.FileUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@Controller("commonFuncController")
@RequestMapping("/func")
public class FuncController {


    @GetMapping("/image")
    private ResponseEntity<byte[]> getImage(String path) throws IOException {
        return FileUtil.getResponseEntity(path);
    }

    @GetMapping("/file/a")
    private ResponseEntity<byte[]> getAFile(String path) throws IOException {
        return FileUtil.getResponseEntity(path);
    }

    @GetMapping("/file/ajax")
    private ResponseEntity<byte[]> getAjaxFile(String path) throws IOException {
        File file=new File(path);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        String fileName= URLEncoder.encode(FileUtil.getFileName(path)+"."+FileUtil.getFileExt(path),"utf-8");
        httpHeaders.setContentDispositionFormData("attachment",fileName);
        return new ResponseEntity<>(FileCopyUtils.copyToByteArray(file), httpHeaders, HttpStatus.CREATED);
    }

}
